#!/usr/bin/env python
# coding:utf-8

from __future__ import absolute_import

import imp,os

from main.units.interfaces import ArgumentError, Backup


class PluginModel(object):
    name = ''
    class_name = ''
    doc = ''
    desc = ''


def _import(filename):
    (path, name) = os.path.split(filename)
    (name, ext) = os.path.splitext(name)

    (file, filename, data) = imp.find_module(name, [path])
    return imp.load_module(name, file, filename, data)


def get_plugins(pathname, interfaceName):

    if not interfaceName:
        raise ArgumentError(interfaceName, 'interfaceName can not be None.')

    lst = []
    for module in (mod for mod in os.listdir(pathname) if mod.endswith('.py')):
        m = _import(os.path.join(pathname, module))
        for s in dir(m):
            att = getattr(m, s)
            if type(att) == type and issubclass(att, interfaceName) \
                    and (hasattr(att, 'desc') and not getattr(att, 'name') == None):
                pm = PluginModel()
                pm.name = getattr(att, 'name')
                pm.class_name = att.__name__
                pm.doc = att.__doc__
                pm.desc = att.desc
                lst.append(pm)
    return lst

def get_plugins_choices_list():
    """为model-backuptask提供choice选项"""
    import main.functions.backup_plugins as plugins
    import os
    pathname = os.path.dirname(plugins.__file__)
    lst = get_plugins(pathname, Backup)

    r = []
    for l in lst:
        r.append((l.name, l.desc))

    return r

def get_task_plugin(backup_task_name):
    ''' 获取指定名称的任务的实例'''
    from main.functions import backup_plugins
    pathname = os.path.dirname(backup_plugins.__file__)
    for module in (mod for mod in os.listdir(pathname) if mod.endswith('.py')):
        m = _import(os.path.join(pathname, module))
        for s in dir(m):
            att = getattr(m, s)
            if type(att) == type and issubclass(att, Backup) \
                and getattr(att,'name')==backup_task_name and hasattr(att, 'desc'):
                return att

def get_all_plugins():
    import main.functions.backup_plugins as plugins
    import os
    pathname = os.path.dirname(plugins.__file__)

    return get_plugins(pathname, Backup)


if __name__ == '__main__':
    import main.functions.backup_plugins as plugins
    import os
    pathname = os.path.dirname(plugins.__file__)

    print get_plugins(pathname, Backup)
